import { element } from 'protractor'
import { addClassName, removeClassName } from 'app/shared/utils/dom-helpers'
import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-role-authorize',
  templateUrl: './role-authorize.component.html'
})
export class RoleAuthorizeComponent implements OnInit {
  page_title: string = '菜单'
  pageType: string = ''
  roleId: string = '' //角色id
  roleName: string = '' //角色名称
  curPage: number = 0 //缓存页码
  menuIds: any = []
  companyCar: any = []
  searchKey: string = '' //树形图查询关键字
  companyIds: any = [] //公司ID
  carSelectedIds: any = [] //车辆ID
  railSelectedIds: any = [] //选中围栏ID
  searchCurrentIndex = 1 // 当前定位车辆的下标
  componentList: any = [
    {
      text: '安装统计',
      id: 'installStatistics',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '续费统计',
      id: 'renewStatistics',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '维修统计',
      id: 'repairStatistics',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '安装厂区详情',
      id: 'installFactoryDetails',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '续费厂区详情',
      id: 'renewFactoryDetails',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '维修厂区详情',
      id: 'repairFactoryDetails',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '库存厂区详情(实时)',
      id: 'inventoryFactoryDetails',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '安装车辆地图',
      id: 'installCarMap',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '热库数据总量',
      id: 'databaseSum',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '小程序人数统计[总注册|总访问]',
      id: 'miniProgram',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: 'API接口调用[前天|昨天|今天]',
      id: 'apiInvoke',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '运载里程',
      id: 'carryDistance',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '运载重量',
      id: 'carryWeight',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '运载次数',
      id: 'carryCount',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '车辆总数',
      id: 'totalCarNumber',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '在线车辆数',
      id: 'onlineCarNumber',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '离线车辆数',
      id: 'offlineCarNumber',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '车辆在线率',
      id: 'onlineRate',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '流量统计图(分)',
      id: 'trafficEchartsMins',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '流量统计图(时)',
      id: 'trafficEchartsDay',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: '用户API调用排名Top5',
      id: 'userApiInvoke',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    },
    {
      text: 'API调用排名Top5',
      id: 'apiInvokeRank',
      state: {
        disabled: false,
        opened: true,
        selected: false
      }
    }
  ]
  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.roleId = queryParams.id
      this.pageType = queryParams.type
      this.roleName = queryParams.roleName
      this.curPage = queryParams.nowPage
    })
  }

  // 往下找搜索内容 0是向上 1是向下
  arrowClick(type = 0) {
    const jsTreeSearch = $('.jstree-search')
    const searchResult = jsTreeSearch.length
    if (searchResult < 1) {
      return
    }
    if (type === 0) {
      if (this.searchCurrentIndex - 1 < 0) {
        this.jsonApiService.message('目前已经在开始位置')
        return
      }
      this.searchCurrentIndex -= 1
    } else {
      if (this.searchCurrentIndex + 1 > searchResult - 1) {
        this.jsonApiService.message('目前已经在结束位置')
        return
      }
      this.searchCurrentIndex += 1
    }
    let lastIndex = 0
    if (type === 1) {
      lastIndex = this.searchCurrentIndex - 1
    } else {
      lastIndex = this.searchCurrentIndex + 1
    }
    const lastElement = jsTreeSearch.eq(lastIndex)[0]
    const allTarget = jsTreeSearch.eq(this.searchCurrentIndex)
    this.scrollToCurrentPosition(allTarget[0], allTarget, $('#tree_content'), lastElement)
  }

  scrollToCurrentPosition(target, allElement, container, beforeTarget = null) {
    if (beforeTarget) {
      removeClassName(beforeTarget, 'jstree-searchCheck')
    }
    addClassName(target, 'jstree-searchCheck')
    container.scrollTop(allElement.offset().top - container.offset().top + container.scrollTop())
    container.animate({
      scrollTop:
        allElement.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
    })
  }

  //tree search功能
  table_search() {
    const searchCheckElement = $('#tree').find('.jstree-searchCheck')[0]
    if (searchCheckElement) {
      removeClassName(searchCheckElement, 'jstree-searchCheck')
    }
    if (!this.searchKey) {
      return
    }
    this.searchCurrentIndex = 0
    $('#tree').jstree(true).search(this.searchKey)
    const jsTreeSearch = $('.jstree-search')
    let searchResult = jsTreeSearch.length
    if (searchResult < 1) {
      this.jsonApiService.message('没有对应数据')
      return
    }
    this.scrollToCurrentPosition(jsTreeSearch[0], jsTreeSearch, $('#tree_content'))
  }
  //展开tree
  allOpen() {
    $('#tree').jstree(true).open_all()
  }
  //折叠tree
  allClose() {
    $('#tree').jstree(true).close_all()
  }
  //全选
  isAllSelect: boolean = false //是否是全部选中
  allCheck() {
    if (this.isAllSelect) {
      $('#tree').jstree(true).uncheck_all()
    } else {
      $('#tree').jstree(true).check_all()
    }
    this.isAllSelect = !this.isAllSelect
  }

  //初始化拉取数据(下拉列表)
  initdata() {
    var that = this
    $('#tree').jstree({
      core: {
        data: function (obj, callback) {
          var jsonstr = '[]'
          var jsonarray = eval('(' + jsonstr + ')')
          var url = ''
          if (that.pageType === '菜单') {
            url = 'resource/resourceTreeSelectForRole.html'
          } else if (that.pageType === '车辆') {
            url = 'role/carTreeSelectForRole.html'
          } else if (that.pageType === '绑定') {
            url = 'role/addCompanyRoleConfigUI.html'
          } else if (that.pageType === '围栏') {
            url = 'role/mapMarkerTreeSelectForRole.html'
          } else if (that.pageType === '首页') {
            url = 'role/getControlStationComponentByRoleId.html'
          }
          $.ajax({
            type: 'GET',
            url: config.BaseURL + url + '?roleId=' + that.roleId,
            dataType: 'json',
            xhrFields: {
              withCredentials: true
            },
            success: function (data) {
              var result = data.data
              if (that.pageType === '首页') {
                if (result.length === 0) {
                  jsonarray = that.componentList
                } else {
                  let valueList = JSON.parse(JSON.stringify(that.componentList))
                  result.forEach(el => {
                    valueList.forEach(list => {
                      if (el === list.id) {
                        list.state.selected = true
                      }
                    })
                  })
                  jsonarray = JSON.parse(JSON.stringify(valueList))
                }
              } else {
                this.companyCar = result
                if (result[0].remark === 'company' || result[0].remark === 'car') {
                  for (let i = 0; i < result.length; i++) {
                    if (result[i].state.selected && result[i].remark === 'company') {
                      this.getChildren(result[i], i) //处理没有子级的选项状态
                    }
                  }
                }
                jsonarray = that.companyCar
              }

              callback.call(this, jsonarray)
            }.bind(this)
          })
        }.bind(this),
        themes: {
          responsive: true
        },
        worker: true, // 将尽可能使用 web worker（译注：理解为多线程） 来解释接收到的 JSON 数据， 这样的好处是有较大的请求时，不容易使 UI 变卡顿
        multiple: true,
        animation: 200,
        dblclick_toggle: true,
        expand_selected_onload: false // 是否在加载树时打开所有选中的节点
      },
      checkbox: {
        keep_selected_style: false,
        three_state: true, //父子级别级联选择
        cascade: 'down'
      },
      plugins: ['checkbox', 'search']
    })

    // $('#tree').on('ready.jstree', function (e, data) {
    // 	console.log('ready.jstree')
    // 	// for(let car of this.companyCar){
    // 	// 	$('#factoryDeviceTree').jstree("_append_json_data","#"+car.parent,this.companyCar, function(){
    // 	//   		// 这个回调函数要加  不然会报错，即使这个函数里面什么也不做
    // 	// 	})
    //   	// }
    // 	// $('#tree').jstree("_append_json_data","#59bd13a96c8da407601b5e86",this.companyCar, function(){
    // 	// // 这个回调函数要加  不然会报错，即使这个函数里面什么也不做
    // 	// })
    // })
  }
  getChildren(val, i) {
    for (let j = 0; j < this.companyCar.length; j++) {
      if (val.id === this.companyCar[j].parent) {
        this.companyCar[i].state.selected = false
        break
      }
    }
  }
  getParents(treeObj, nodeObj) {
    var parentId = treeObj.get_parent(nodeObj)
    // if(this.pageType === '车辆'){
    // 	if(nodeObj.original.remark === 'company'&&!this.companyIds.includes(nodeObj.id)){
    // 		this.companyIds.push(nodeObj.id);
    // 	}else if(nodeObj.original.remark === 'car'){
    // 		this.carSelectedIds.push(nodeObj.id);
    // 		if(!this.companyIds.includes(nodeObj.parent)){
    // 			this.companyIds.push(nodeObj.parent);
    // 		}
    // 	}
    // 	if (parentId != "#") {
    // 		this.getParents(treeObj, treeObj.get_node(parentId));
    // 	}
    // } else{
    // 	if(this.pageType === '围栏'){
    // 		if(nodeObj.original.remark === 'mapMarker'){
    // 			this.railSelectedIds.push(nodeObj.id);
    // 		}
    // 	}
    //  	if (parentId != "#") {
    // 		if(!this.menuIds.includes(parentId)){
    // 			this.menuIds.push(parentId);
    // 		}
    // 		this.getParents(treeObj, treeObj.get_node(parentId));
    // 	}
    // }
    if (this.pageType === '围栏') {
      if (nodeObj.original.remark === 'mapMarker') {
        this.railSelectedIds.push(nodeObj.id)
      }
    }
    if (parentId != '#') {
      if (!this.menuIds.includes(parentId)) {
        this.menuIds.push(parentId)
      }
      this.getParents(treeObj, treeObj.get_node(parentId))
    }
  }
  unique() {

  }

  //权限数据保存
  saveDate() {
    var url = ''
    var reqdata = ''
    this.menuIds = []
    this.companyIds = []
    this.carSelectedIds = []
    this.railSelectedIds = []
    var tree = $('#tree').jstree(true)
    if (this.pageType === '车辆') {
      const checkedIds = []
      const allCheckedNode = tree.get_checked(true) // 获取所有选中的节点（半选不算），true 返回对象，false 返回id
      // console.log('allCheckedNode', allCheckedNode)
      for (let i = 0; i < allCheckedNode.length; i++) {
        const checkedNode = allCheckedNode[i]
        let parents = []
        if (checkedNode.parents) { // node.parents 可以拿到当前节点的所有父级节点 id（在车辆列表时为公司节点，只有公司才能有子集）
          parents = checkedNode.parents.filter(item => item !== '#') // 过滤掉最顶层的 #，一般这个节点代表根节点了
        }
        checkedIds.push(checkedNode.id, ...parents) // 将选中的节点及父节点都加入到数组，方便去重和分类
      }
      const uniqueCheckedIds = Array.from(new Set(checkedIds)) // Set 得到去重后的 id
      for (let i = 0; i < uniqueCheckedIds.length; i++) {
        const checkedId = uniqueCheckedIds[i]
        if (checkedId.length > 20) { // id 长度大于 20 则是公司节点，反之是车辆
          this.companyIds.push(checkedId)
        } else {
          this.carSelectedIds.push(checkedId)
        }
      }

      if (this.carSelectedIds.length < 1) {
        this.jsonApiService.message('至少分配一条车辆数据')
        return
      }
      url = 'role/updateCarPermissionForRole.html'
      reqdata =
        'roleId=' +
        this.roleId +
        '&deviceIds=' +
        this.carSelectedIds.join(',') +
        '&companyIds=' +
        this.companyIds.join(',')
    } else {
      var selectedIds = tree.get_checked() //获取所有选中节点id
      var selected = tree.get_checked(true) //获取所有选中节点数据
      if (this.pageType !== '首页') {
        for (var i = 0; i < selected.length; i++) {
          this.getParents(tree, selected[i])
        }
      }
      if (this.pageType === '菜单') {
        let temResourceIds = new Set(selectedIds.concat(this.menuIds)) //合并去重
        let resourceIds = Array.from(temResourceIds).join(',') //Set转Array
        if (!resourceIds) {
          this.jsonApiService.message('至少分配一条菜单数据')
          return
        }
        url = 'resource/updateResourcePermissionForRole.html'
        reqdata = 'roleId=' + this.roleId + '&resourceIds=' + resourceIds
      } else if (this.pageType === '绑定') {
        let temResourceIds = new Set(selectedIds.concat(this.menuIds)) //合并去重
        let resourceIds = Array.from(temResourceIds).join(',') //Set转Array
        if (!resourceIds) {
          this.jsonApiService.message('至少绑定一条公司数据')
          return
        }
        url = 'role/companyRoleConfig'
        reqdata = 'roleId=' + this.roleId + '&companyIds=' + resourceIds
      } else if (this.pageType === '围栏') {
        let temResourceIds = new Set(selectedIds.concat(this.menuIds)) //合并去重
        let railIds = Array.from(temResourceIds).join(',') //Set转Array
        if (!this.railSelectedIds.join(',')) {
          this.jsonApiService.message('至少分配一条围栏数据')
          return
        }
        url = 'role/updateMapMarkerPermissionForRole.html'
        reqdata = 'roleId=' + this.roleId + '&mapMarkerIds=' + railIds
      } else if (this.pageType === '首页') {
        if (selectedIds.length === 0) {
          this.jsonApiService.message('至少分配一条首页数据')
          return
        }
        let railIds = Array.from(selectedIds).join(',') //Set转Array
        url = 'role/updateControlStationPermissionForRole.html'
        reqdata = 'roleId=' + this.roleId + '&componentList=' + railIds
      }
    }
    this.jsonApiService.http(url, reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.router.navigate(['/system/role'], { queryParams: { nowPage: this.curPage } })
      }
    })
  }
  //返回
  goBack() {
    this.router.navigate(['/system/role'], { queryParams: { nowPage: this.curPage } })
  }
  ngOnInit() {
    System.import('assets/js/jstree/jstree.min.js').then(() => {
      this.initdata()
    })
  }
}
